package cn.flying.cloud.base.interceptor;

import javax.servlet.http.HttpServletRequest;

import java.util.UUID;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import feign.RequestInterceptor;
import feign.RequestTemplate;

import cn.flying.cloud.base.common.constants.Constants;
import cn.flying.cloud.base.common.utils.Ft;

/**
 * Feign调用拦截处理
 *
 * @author: admin
 * @date: 2024年05月27日 11:13
 * @version: 1.0
 */
@Configuration
public class GlobalFeignRequestInterceptor implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate template) {
        // 这里可以从当前线程上下文、MDC等地方获取traceId，示例中直接使用固定值
        String traceId = MDC.get(Constants.TRAC_ID);
        if (StringUtils.isNotBlank(traceId)) {
            traceId = UUID.randomUUID().toString().replaceAll("-", "");
        }
        template.header(Constants.TRAC_ID, traceId);

        RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
        if (attributes != null) {
            HttpServletRequest request = ((ServletRequestAttributes) attributes).getRequest();
            template.header("User-Agent", request.getHeader("User-Agent"));
            template.header("Authorization", request.getHeader("Authorization"));
            template.header("X-Real-IP", request.getHeader("X-Real-IP"));
            template.header("X-Forwarded-For", request.getHeader("X-Forwarded-For"));
        }
        template.header(Constants.TENANT_ID, Ft.Local.TenantId());
        template.header(Constants.USER_ID, Ft.Local.UserId());
        template.header(Constants.USER_NAME, Ft.Local.UserName());
        template.header(Constants.REQUEST_ID, Ft.Local.RequestId());
        template.header(Constants.ENV_ID, Ft.Local.EnvId());
    }
}